<template>
  <div class="gl_heightFull gl_contentBox">
    <el-button type="success" :disabled="disbtn" size="mini" style="margin-bottom:15px" @click="addstudent()">添加学员</el-button>
    <!-- <el-button type="success" :disabled="disbtn" size="mini" style="margin-bottom:15px" @click="addstudent()">保存名单</el-button> -->
    <el-button type="success" :disabled="disbtn" size="mini" :loading="payLoading" style="margin-bottom:15px" @click="clickPay()">提交支付</el-button>
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :md="4" :lg="4">
          <p>考生姓名</p>
          <el-input v-model="Api_GET_ClubFeeStudentQO.Filter" placeholder="请输入考生姓名" size="mini" clearable @change="gettablelist()" />
        </el-col>
        <!-- <el-col :md="4" :lg="4">
          <p>缴费结果</p>
          <el-select v-model="Isstate" size="mini" @change="gettablelist()">
            <el-option label="全部" value="" />
            <el-option v-for="(item,index) in dict.feeStudentStatus" :key="index" :label="item.value" :value="item.code" />
          </el-select>
        </el-col> -->
        <el-col :md="4" :lg="4">
          <el-button type="primary" style="margin-top:25px" size="mini" @click="gettablelist()">筛选</el-button>
          <el-button type="warning" size="mini" @click="reset()">{{ $t('button.Reset') }}</el-button>
        </el-col>
      </el-row>
    </div>

    <div style="margin-top:15px">
      <el-table v-loading="tableLoading" class="gl_table_noBorder" size="mini" :data="tableData">
        <el-table-column label="序号" type="index" align="center" width="55" />
        <el-table-column label="姓名" width="54">
          <template slot-scope="{row}">
            <!-- <img class="roodsPhoto" :src="getStaticFileUrl(row.avatarUrl)" alt=""> -->
            <PersonalImage :imgurl="row.avatarUrl" imgheight="60px" />
          </template>
        </el-table-column>
        <el-table-column prop="registerStudent.name" />
        <el-table-column label="证件号码" prop="registerStudent.idCardNumber" />
        <el-table-column label="缴纳类型" align="center">
          <template slot-scope="{row}">
            <span v-if="row.memberFeeTypeCode">{{ row.memberFeeTypeCode === 'New'?'新增':'续费' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="中跆协会员号" align="center" prop="memberNumber" />
        <el-table-column label="缴纳年限" align="center" prop="feeYear" />
        <el-table-column label="机构" align="center">
          <template slot-scope="{ row }">
            <el-popover placement="bottom" width="180" trigger="hover" :content="row.organizationUnitName">
              <div slot="reference" class="nav_left_top">{{ row.organizationUnitName }}</div>
            </el-popover>
          </template>

        </el-table-column>
        <el-table-column label="缴费金额" align="center" prop="amount">
          <template slot-scope="{ row }">
            <span>
              {{ parseFloat( row.amount * 100) / 10000 }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="缴费结果" align="center" prop="name">
          <template slot-scope="{row}">
            <span v-for="(item, index) in dict.feeStudentStatus" :key="index">{{ item.code == row.statusCode ? item.value : '' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="180">
          <template slot-scope="{ row }">
            <el-button size="mini" :disabled="disbtn" type="text" @click="todetail(row)">编辑</el-button>
            <el-button size="mini" :disabled="disbtn" type="text" @click="close(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 支付方式弹出层 -->
    <el-dialog class="gl_dialog_TitleLine" title="选择支付方式" :visible.sync="dialogVisibleForPay" :close-on-click-modal="false" width="650px">
      <div v-loading="modalPayLoding" class="pay_type_list">
        <div v-if="paytype.isOpenOfflinePay" class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline()">线下支付</div>
        <div v-if="paytype.isOpenOnlinePay" class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline()">线上支付</div>
      </div>
    </el-dialog>
    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>

    <el-dialog
      class="gl_dialog_TitleLine"
      title="线下收款账户信息"
      width="640px"
      :visible.sync="offlineDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <offline-pay-info :offline-data="offlineData" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="jumpToOrderCenter">前往订单中心</el-button>
      </div>
    </el-dialog>
    <el-row class="gl_pt_15" style="text-align: right;">
      <el-pagination
        :current-page="Api_GET_ClubFeeStudentQO.Page"
        :page-size="Api_GET_ClubFeeStudentQO.MaxResultCount"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>
  </div>
</template>

<script>
import PersonalImage from '@/components/PersonalImage/index';
import {
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';
import OfflinePayInfo from '@/components/OfflinePayInfo';
import { mapState, mapActions } from 'vuex';
import { api_GET_ClubFeeStudent, api_GET_ClubFeeStudentFeeRequestOrderFeeRequestId, api_DELETE_ClubFeeStudentId, api_POST_ClubFeeStudentSubmitMembershipFeeFeeRequestId, api_GET_ClubFeeStudentDuanExamPayInfoFeeRequestId } from '@/extend/api/hallswaggerApi/app.js';
import { Api_GET_ClubFeeStudentQO } from '@/lib/form/hall/swaggerForm';
import {
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息,
  api_GET_TradePayOrderParameter // 获取支付订单的参数
} from '@/extend/api/swaggerApi/app';
export default {
  components: {
    OfflinePayInfo,
    PersonalImage
  },
  data() {
    return {
      orderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      orderNo: '', // 订单编号
      topay: false,
      disbtn: false,
      offlineData: {},
      paytype: {
        isOpenOnlinePay: false,
        isOpenOfflinePay: false
      }, // 支付方式
      offlineDialogVisible: false,
      modalPayLoding: false,
      dialogVisibleForPay: false,
      tableData: [],
      tableLoading: false,
      IsEnabled: '',
      Isstate: '',
      totalPage: 0,
      freeDate: [],
      Api_GET_ClubFeeStudentQO: new Api_GET_ClubFeeStudentQO(), // 缴费学员数据
      payLoading: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      user: state => state.user.currentOU
    })
  },
  created() {
    this.getDict();
    this.gettablelist();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 获取考试审核列表
    gettablelist(page) {
      this.Api_GET_ClubFeeStudentQO.StatusCode = this.Isstate;
      this.Api_GET_ClubFeeStudentQO.IncludeRegisterStudent = true;
      this.Api_GET_ClubFeeStudentQO.IncludeRequest = true; // type: boolean
      this.Api_GET_ClubFeeStudentQO.IncludeRegisterStudent = true; // type: boolean
      this.Api_GET_ClubFeeStudentQO.IncludeIdCardType = true; // type: boolean
      this.Api_GET_ClubFeeStudentQO.IncludeMemberFeeType = true; // type: boolean
      this.Api_GET_ClubFeeStudentQO.IncludeStatus = true; // type: boolean
      this.Api_GET_ClubFeeStudentQO.FeeRequestId = this.$route.query.id; // type: boolean
      this.tableLoading = true;
      this.Api_GET_ClubFeeStudentQO.Page = page || 1;
      this.Api_GET_ClubFeeStudentQO.SkipCount = (this.Api_GET_ClubFeeStudentQO.Page - 1) * this.Api_GET_ClubFeeStudentQO.MaxResultCount;
      api_GET_ClubFeeStudent(this.Api_GET_ClubFeeStudentQO).then(res => {
        console.log(res);
        this.totalPage = res.totalCount;
        this.tableData = res.items;
        this.tableLoading = false;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
      api_GET_ClubFeeStudentFeeRequestOrderFeeRequestId(this.$route.query.id).then(res => {
        console.log(res);
        console.log(res === '');
        if (res === '') {
          this.disbtn = false;
        } else {
          this.disbtn = true;
        }
      });
    },
    // 切换考试日期
    changeAttendance (val) {
      // const _start = val ? val[0] : null;
      // const _end = val ? val[1] : null;
      // const _qucikDateCode = this.matchQuickDate(_start, _end);
      // this.currentQuickDate = _qucikDateCode;
      this.gettablelist();
    },
    // 删除按钮
    close(id) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubFeeStudentId(id).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.gettablelist();
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        });
    },
    // 新增会员费缴纳
    openMemberfee() {
      this.$refs.AddMembership.dialogVisible = true;
    },
    // 打开详情
    todetail(row) {
      this.$router.push({ name: 'Editfeestudent', query: { id: this.$route.query.id, registerStudentId: row.id }});
    },
    // 分页按钮
    sizeChange(MaxResultCount) {
      this.Api_GET_ClubFeeStudentQO.MaxResultCount = MaxResultCount;
      this.gettablelist();
    },
    pageIndexChange(currentPage) {
      this.gettablelist(currentPage);
    },
    // 重置按钮
    reset () {
      this.Isstate = '';
      this.Api_GET_ClubFeeStudentQO = new Api_GET_ClubFeeStudentQO();
      this.gettablelist();
    },
    // 添加学员
    addstudent() {
      this.$router.push({ name: 'Addfeestudent', query: { id: this.$route.query.id }});
    },
    // 点击支付按钮
    clickPay () {
      if (this.tableData.length === 0) {
        this.$message({ type: 'warning', message: '未添加学员' });
        return;
      }
      this.payLoading = true;
      api_GET_ClubFeeStudentDuanExamPayInfoFeeRequestId(this.$route.query.id).then(res => {
        console.log(res);
        if (res.isOpenOfflinePay === false && res.isOpenOnlinePay === false) {
          this.$message({ type: 'warning', message: '未设置收款账号' });
          this.payLoading = false;
        } else {
          this.paytype = res;
          if (this.paytype.isOpenOfflinePay || this.paytype.isOpenOnlinePay) {
            // 单一支付方式直接跳转支付页面
            if (!(this.paytype.isOpenOfflinePay && this.paytype.isOpenOnlinePay)) {
              this.paytype.isOpenOfflinePay ? this.clickPayOffline() : this.clickPayOnline();
            } else {
              this.payLoading = false;
              this.dialogVisibleForPay = true;
            }
          } else {
            this.payLoading = false;
            this.$message({ type: 'warning', message: '未设置收款账号' });
          }
          // if (res.isOpenOfflinePay === false && res.isOpenOnlinePay === false) {
          //   this.dialogVisibleForPay = false;
          //   this.$message({ type: 'warning', message: '未设置收款账号' });
          // } else {
          //   this.dialogVisibleForPay = true;
          // }
        }
      }, error => {
        this.payLoading = false;
        this.$message({ type: 'error', message: `订单创建失败！${error.error.message}` });
        this.dialogVisibleForPay = false;
        this.modalPayLoding = false;
      });
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 线下支付
    clickPayOffline () {
      //  paytype: {
      //   isOpenOnlinePay: false,
      //   isOpenOfflinePay: false,
      // },
      if (!this.paytype.isOpenOfflinePay) {
        this.$message({ type: 'error', message: '未设置线下支付' });
        return;
      }
      this.topay = false;
      this.submitOrder();
    },
    clickPayOnline() {
      if (!this.paytype.isOpenOnlinePay) {
        this.$message({ type: 'error', message: '未设置线上支付' });
        return;
      }
      this.topay = true;
      this.submitOrder();
    },
    // 提交订单
    submitOrder() {
      const _json = {};
      this.dialogVisibleForPay = false;
      if (this.topay) {
        // 如果是线上支付
        _json.isOnlinePayment = true;
      } else {
        // 线下支付，展示获取订单信息，展示收款账户信息
        _json.isOnlinePayment = false;
      }
      this.modalPayLoding = true;
      api_POST_ClubFeeStudentSubmitMembershipFeeFeeRequestId(this.$route.query.id, _json).then(res => {
        this.payLoading = false;
        this.orderNo = res.orderNo;
        if (this.topay) {
        // 如果是线上支付
          this.payment(res.orderNo);
        } else {
        // 线下支付，展示获取订单信息，展示收款账户信息
          this.getOrderDetails(res.orderNo);
        }
        this.modalPayLoding = false;
      }, error => {
        this.payLoading = false;
        this.$message({ type: 'error', message: `订单创建失败！${error.error.message}` });
        this.modalPayLoding = false;
      });
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo }).then(res => {
        res._orderNo = orderNo;
        this.offlineData = res;
        this.offlineDialogVisible = true;
      }).catch(error => {
        this.$message({ type: 'error', message: `订单详情获取失败！${error.error.message}` });
      });
    },
    // 去支付
    payment(orderNo) {
      if (orderNo) {
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        // const _orderUrl = '#/myCenter/order';
        const _orderUrl = '#/' + this.$route.params.tenantId + '/order/expenditure/';
        const url = _origin + _pathname + _orderUrl;
        this.orderParameterQO.OrderNo = orderNo;
        this.orderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(this.orderParameterQO)
          .then(res => {
            this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            this.$refs.form.submit();
          });
      }
    },
    jumpToOrderCenter() {
      this.$router.push({ name: 'Expenditure' });
    }
  }

};
</script>

<style lang="scss" scoped>
.pay_type.van-popup {
  background-color: transparent;
  z-index: 3015 !important; /* 覆盖组件原有层级，避免与summary弹层冲突 */
}
.pay_type_list {
  display: flex;
  justify-content: space-around;
}
.pay_type_item {
  width: 260px;
  height: 84px;
  padding: 0 50px;
  margin-bottom: 12px;
  text-align: right;
  color: #fff;
  font-size: 24px;
  line-height: 84px;
  cursor: pointer;
}
.pay_type_item:last-child {
  margin-bottom: 0;
}
.pay_type_online {
  background-image: url('../../../../assets/images/pay/online.png');
  background-repeat: no-repeat;
}
.pay_type_offline {
  background-image: url('../../../../assets/images/pay/offline.png');
  background-repeat: no-repeat;
}
  .roodsPhoto{
    width: 60px;
    height: 60px;
    vertical-align: middle;
  }
     .nav_left_top{
     white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
   }
</style>
